package eerbaar.v2.pattern.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eerbaar.game.IGame;
import eerbaar.shared.exceptions.GameException;
import eerbaar.shared.persist.ISerializerService;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.v2.gamebuilder.GamePacket;
import eerbaar.v2.pattern.ProgramPacket;

@SuppressWarnings("serial")
public class PatternServiceImpl extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        try {
            String key = request.getHeader("key");
            String action = request.getHeader("action");
            if ("generateProgram".equalsIgnoreCase(action)) {

                BufferedReader reader = request.getReader();
                String line = reader.readLine();
                ISerializerService service = ServiceFactory
                        .getService(ISerializerService.class);
                IGame game = service.load(IGame.class, line);

                GamePacket old = new GamePacket();
                old.setGame(game);

                ProgramPacket packet = generateProgram(key, old);

                PrintWriter writer = response.getWriter();
                response.setHeader("success", "" + packet.wasSuccessful());
                response.setHeader("temporaryName", packet.getTemporaryName());

                writer.append(packet.getProgram());
            }

        } catch (GameException e) {
            e.printStackTrace();
        }
    }

    public ProgramPacket generateProgram(String key, GamePacket packet)
            throws GameException {

        ProgramPacket result = new ProgramPacket();

        IGame game = packet.getGame();

        EventPlayback learner = new EventPlayback();
        INode idea = learner.findProgram(game);

        if (idea != null) {

            result.setSuccess(true);
            result.setTemporaryName(idea.getPayload().getKey());
            result.setProgram(idea.getPayload().getValue());

            System.out.println(idea.getPayload().getValue());
        }

        return result;
    }

}
